package com.oyjd.fw.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 压缩/解压缩文件,支持中文名
 * 
 * @author <b>欧建东<br/>
 *         Email:oyjd@163.com</b>
 * 
 */
public class ZipUtil {
	private static final int buffer = 10240;

	/**
	 * 解压文件
	 * 
	 * @param file
	 * @param savePath
	 */
	public static void unZip(File file, String savePath) {
		try {
			ZipFile zipFile = new ZipFile(file, "gb2312");
			Enumeration<?> entries = zipFile.getEntries();
			while (entries.hasMoreElements()) {
				byte[] buf = new byte[buffer];
				ZipEntry entry = (ZipEntry) entries.nextElement();
				String fileName = entry.getName();
				int index = fileName.lastIndexOf("/");
				if (index > -1) {
					fileName = fileName.substring(index + 1);
				}
				fileName = savePath + "/" + fileName;

				InputStream is = zipFile.getInputStream(entry);

				FileOutputStream fos = new FileOutputStream(new File(fileName));
				BufferedOutputStream bos = new BufferedOutputStream(fos, buffer);
				int count = -1;
				while ((count = is.read(buf)) > -1) {
					bos.write(buf, 0, count);
				}
				bos.close();
				is.close();
			}
			zipFile.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 压缩文件
	 * 
	 * @param os
	 * @param basePath
	 * @throws Exception
	 */
	public static void zip(OutputStream os, String basePath) throws Exception {
		ZipOutputStream out = new ZipOutputStream(os);
		out.setEncoding("GBK");
		zip(out, new File(basePath), "");
		out.close();
	}

	/**
	 * 打包文件
	 * 
	 * @param out
	 *            输出流
	 * @param f
	 *            目标文件夹或文件
	 * @param base
	 *            目标文件基础路径，默认为空
	 * @throws Exception
	 */
	private static void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fs = f.listFiles();
			if (fs != null && fs.length > 0) {
				if (null != base && !"".equals(base)) {
					out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
					base = base + "/";
				} else {
					base = "";
				}
				for (File ff : fs) {
					zip(out, ff, base + ff.getName());
				}
			}
		} else {
			out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			byte[] b = new byte[buffer];
			int p;
			while ((p = in.read(b)) != -1) {
				out.write(b, 0, p);
			}
			in.close();
		}
	}
}
